package com.springboot.demo.lock.zookeeper;

import com.springboot.common.lock.Lock;
import java.util.concurrent.TimeUnit;
import org.I0Itec.zkclient.ZkClient;

/**
 * zk锁
 *
 * @author supu
 * @date 2019-03-20 17:41
 **/
public class ZkLock extends BaseDistributedLock implements Lock {
    /**
     * 获取到的锁的路径
     */
    private String lockPath;

    public ZkLock(ZkClient zkClient, String basePath, String lockName) {
        super(zkClient, basePath, lockName);
    }

    @Override
    public void lock() throws Exception {
        tryLock(-1, null);
    }

    @Override
    public boolean tryLock(long time, TimeUnit timeUnit) throws Exception {
        lockPath = attemptLock(time, timeUnit);
        return lockPath != null;
    }

    @Override
    public void unLock() throws Exception {
        releaseLock(lockPath);
    }
}
